/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.serializer;

import at.schauer.gregor.vienna.AbstractViennaIT;
import at.schauer.gregor.vienna.context.ViennaContextManager;
import at.schauer.gregor.vienna.exception.ViennaException;
import at.schauer.gregor.vienna.test.SimpleObject;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

import java.util.*;

import static org.junit.Assert.assertEquals;

/**
 * @author Gregor Schauer
 */
public class DefaultSerializerIT extends AbstractViennaIT {
	@Test
	@SuppressWarnings("unchecked")
	public void test() throws Exception {
		SimpleObject obj = new SimpleObject(null, true, (byte) 1, (char) 1, (short) 1, 1, 1L, 1f, 1.0);
		Class<SimpleObject> type = (Class<SimpleObject>) obj.getClass();
		Serializer<SimpleObject> serializer = ViennaContextManager.getInstance().getContext().getSerializer(type);

		Map<String, Object> map = serializer.save(obj);
		assertEquals(false, map.isEmpty());

		Map describe = BeanUtils.describe(obj);
		describe.put(Serializer.CLASS, obj.getClass().getName());

		SimpleObject load = serializer.load(map);
		assertEquals(obj, load);
	}

	@Test(expected = ViennaException.class)
	public void testInvalidClass() {
		DefaultSerializer<Object> serializer = new DefaultSerializer<Object>();
		serializer.load(DefaultSerializerIT.<String, Object>singletonMap(Serializer.CLASS, ""));
	}

	public static <K, V> Map<K, V> singletonMap(K key, V value) {
		Map<K, V> map = new HashMap<K, V>();
		map.put(key, value);
		return map;
	}

	public static <T> List<T> singletonList(T... objects) {
		List<T> list = new ArrayList<T>();
		list.addAll(Arrays.asList(objects));
		return list;
	}
}
